package cn.jdemo.jsystem.runtime;
/**
 * 虚拟机关闭钩子，注册、移除
 * @see Runtime#addShutdownHook(Thread)
 * @see Runtime#removeShutdownHook(Thread)
 *
 * @date 2020/12/18
 */
public class Demo01_ShutdownHook {
    public static void main(String[] args) {
        test01();
        // test02();
        //test03();
        //test04();
        //test05();
    }

    /**
     * shutdownHook01...
     */
    public static void test01() {
        Thread thread = new Thread(()->{
            System.out.println("shutdownHook01...");
        });
        Runtime.getRuntime().addShutdownHook(thread);
    }

    /**
     *
     */
    public static void test05() {
        Thread thread = new Thread(()->{
            System.out.println("shutdownHook01...");
        });
        Runtime.getRuntime().addShutdownHook(thread);
        Runtime.getRuntime().removeShutdownHook(thread);
    }

    /**
     * Exception in thread "main" java.lang.IllegalArgumentException: Hook previously registered
     * 	at java.lang.ApplicationShutdownHooks.add(ApplicationShutdownHooks.java:72)
     * 	at java.lang.Runtime.addShutdownHook(Runtime.java:211)
     * 	at cn.jdemo.jsystem.runtime.Demo01.test04(Demo01.java:28)
     * 	at cn.jdemo.jsystem.runtime.Demo01.main(Demo01.java:9)
     * shutdownHook01...
     */
    public static void test04() {
        Thread thread = new Thread(()->{
            System.out.println("shutdownHook01...");
        });
        Runtime.getRuntime().addShutdownHook(thread);

        Runtime.getRuntime().addShutdownHook(thread);

        Runtime.getRuntime().removeShutdownHook(thread);
    }

    /**
     *
     * Exception in thread "main" java.lang.IllegalArgumentException: Hook previously registered
     * 	at java.lang.ApplicationShutdownHooks.add(ApplicationShutdownHooks.java:72)
     * 	at java.lang.Runtime.addShutdownHook(Runtime.java:211)
     * 	at cn.jdemo.jsystem.runtime.Demo01.test01(Demo01.java:16)
     * 	at cn.jdemo.jsystem.runtime.Demo01.main(Demo01.java:7)
     * shutdownHook01...
     */
    public static void test03() {
        Thread thread = new Thread(()->{
            System.out.println("shutdownHook01...");
        });
        Runtime.getRuntime().addShutdownHook(thread);

        Runtime.getRuntime().addShutdownHook(thread);

    }

    public static void test02() {
        //ApplicationShutdownHooks 这个类是给Runtime的hooks接口，Runtime类可以利用这个类注册shutdownhooks
        Thread thread = new Thread(()->{
            System.out.println("shutdownHook02...");
        });
        // no-modifer:只有包内类可以放翁
        // ApplicationShutdownHooks.add(thread);
        // Error:(22, 9) java: java.lang.ApplicationShutdownHooks在java.lang中不是公共的; 无法从外部程序包中对其进行访问
    }
}
